﻿using System.Windows;
using System.Windows.Input;
using System.Windows.Controls;
using System.Windows.Interactivity;
using System.Windows.Automation.Peers;
using System.Windows.Automation.Provider;

namespace Thinktecture.UIAnnotations.Behaviors
{
    public class CancelButtonBehavior : TargetedTriggerAction<FrameworkElement>
    {
        protected override void OnAttached()
        {
            base.OnAttached();
            var window = this.AssociatedObject as FrameworkElement;

#if SILVERLIGHT
            window.KeyUp += this.OnKeyUp;
#else
            // set the IsCancel property (in case of WPF)
            if (this.TargetObject != null && this.TargetObject is Button)
            {
                var button = this.TargetObject as Button;
                button.IsCancel = true;
            }
#endif
        }

        protected override void OnDetaching()
        {
            base.OnDetaching();
#if SILVERLIGHT
            var window = this.AssociatedObject as FrameworkElement;
            window.KeyUp -= this.OnKeyUp;
#endif
        }

#if SILVERLIGHT
        private void OnKeyUp(object sender, KeyEventArgs e)
        {
            if (e.Key == Key.Escape && this.TargetObject != null && this.TargetObject is Button)
            {
                var button = this.TargetObject as Button;
                var peer = new ButtonAutomationPeer(button);
                var provider = peer.GetPattern(PatternInterface.Invoke) as IInvokeProvider;
                provider.Invoke();
            }
        }
#endif

        protected override void Invoke(object parameter)
        {
        }
    }
}
